package main

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"
)

const (
	UploadDir   = "./uploads"
	MaxFileSize = 1 << 30 // 1GB
)

func main() {
	// 创建上传目录
	os.MkdirAll(UploadDir, os.ModePerm)

	// 文件上传处理
	http.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != "POST" {
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
			return
		}

		r.ParseMultipartForm(MaxFileSize)
		file, handler, err := r.FormFile("file")
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		defer file.Close()

		// 保存文件
		dstPath := filepath.Join(UploadDir, handler.Filename)
		dst, err := os.Create(dstPath)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer dst.Close()

		if _, err := io.Copy(dst, file); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		fmt.Fprintf(w, "File %s uploaded!", handler.Filename)
	})

	// 文件下载处理
	http.HandleFunc("/download/", func(w http.ResponseWriter, r *http.Request) {
		filename := r.URL.Path[len("/download/"):]
		filePath := filepath.Join(UploadDir, filename)

		w.Header().Set("Content-Disposition", "attachment; filename="+filename)
		http.ServeFile(w, r, filePath)
	})

	// 新增文件列表接口
	http.HandleFunc("/files", func(w http.ResponseWriter, r *http.Request) {
		files, err := os.ReadDir(UploadDir)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		var filenames []string
		for _, file := range files {
			if !file.IsDir() {
				filenames = append(filenames, file.Name())
			}
		}

		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(filenames)
	})

	// 静态文件服务（前端页面）
	http.Handle("/", http.FileServer(http.Dir("./static")))

	fmt.Println("Server running on :8080")
	http.ListenAndServe(":8080", nil)
}
